package com.example.game_app;

import androidx.appcompat.app.AppCompatActivity;

import com.example.game_app.util.Request;
import com.example.game_app.util.UserContext;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends AppCompatActivity {

    private HandlerThread handlerThread;
    private Handler handler;

    private final int REGISTER = 1;
    private final int LOING = 2;

    CheckBox rememberMeCheckbox;
    EditText username, password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        rememberMeCheckbox = findViewById(R.id.checkBox);


        handlerThread = new HandlerThread("http");
        handlerThread.start();

        handler = new HttpHandler(handlerThread.getLooper());// 让handler消息运行子线程

        restoreLoginCredentials(rememberMeCheckbox, username, password);
        rememberMeCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!isChecked) {
                clearRememberedCredentials();
            }
        });
    }

    // 监听类
    private class HttpHandler extends Handler {
        public HttpHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REGISTER:
                    registerUser();
                    break;
                case LOING:
                    loginUser();// 具体的操作
                    break;
                default:
                    break;
            }
        }
    }

    // 点击登录，发送消息到handleMessage，执行消息对应方法
    public void login01(View view) {
        handler.sendEmptyMessage(LOING);
    }

    public void register01(View view) {
        handler.sendEmptyMessage(REGISTER);
    }

    /**
     * 用户登录
     */
    public void loginUser() {
        new Thread() {
            @Override
            public void run() {
                Request request = new Request();
                // 返回用户id
                String result = request.post("/accounts/login", "accountName=" + username.getText() + "&password=" + password.getText());
                if("用户名或密码错误".equals(result)){
                    runOnUiThread(() -> Toast.makeText(LoginActivity.this, result, Toast.LENGTH_SHORT).show());
                }else{
                    // 保存当前用户id到SharedPreferences，以便使用
                    UserContext.setUser(LoginActivity.this,result);
                    Intent intent = new Intent(LoginActivity.this, ViewPagerActivity.class);
                    startActivity(intent);
                }
                // 是否保存用户输入信息到sharedPreferences
                if (rememberMeCheckbox.isChecked()) {
                    saveLoginCredentials(username.getText().toString(), password.getText().toString());
                }
            }
        }.start();

    }
    /**
     * 用户注册
     */
    private void registerUser() {
        new Thread() {
            @Override
            public void run() {
                String result = Request.post("/accounts/register", "accountName=" + username.getText() + "&password=" + password.getText());
                if ("".equals(result)) {
                    Intent intent = new Intent(LoginActivity.this, LoginActivity.class);
                    startActivity(intent);
                    runOnUiThread(() -> Toast.makeText(LoginActivity.this, "注册成功", Toast.LENGTH_SHORT).show());
                } else {
                    runOnUiThread(() -> Toast.makeText(LoginActivity.this, result, Toast.LENGTH_SHORT).show());
                }
            }
        }.start();
    }
    /**
     * 记住密码时，记录当前输入的状态
     * @param rememberMeCheckbox
     * @param username
     * @param password
     */
    private void restoreLoginCredentials(CheckBox rememberMeCheckbox, EditText username, EditText password) {
        SharedPreferences sp = getSharedPreferences("UserPreferences", MODE_PRIVATE);
        String savedUsername = sp.getString("username", "");
        String savedPassword = sp.getString("password", "");
        boolean rememberMe = sp.getBoolean("remember_me", false);
        if (rememberMe) {
            username.setText(savedUsername);
            password.setText(savedPassword);
            rememberMeCheckbox.setChecked(true);
        }
    }
    private void saveLoginCredentials(String username, String password) {
        SharedPreferences sp = getSharedPreferences("UserPreferences", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("username", username);
        editor.putString("password", password);
        editor.putBoolean("remember_me", true);
        editor.apply();
    }

    private void clearRememberedCredentials() {
        SharedPreferences sp = getSharedPreferences("UserPreferences", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove("username");
        editor.remove("password");
        editor.putBoolean("remember_me", false);
        editor.apply();
    }


}